/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.common.biz.aspectj;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import static com.comac.ins.common.core.constant.Constants.TRACE_ID;

/**
 * @author zhanghongyi
 * @date 2024/9/4
 * @description TraceIdAspect
 */
@Component
@Aspect
@Order(0)
public class TraceIdAspect {

    @Pointcut(value = "execution(public * com.comac.ins..*.*Controller*.*(..))")
    public void pointCut() {
    }
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String oldTraceId = MDC.get(TRACE_ID);
        if (StringUtils.isBlank(oldTraceId)) {
            MDC.put(TRACE_ID, UUID.randomUUID().toString());
        }
        try {
            return proceedingJoinPoint.proceed();
        } finally {
            if (StringUtils.isBlank(oldTraceId)) {
                MDC.remove(TRACE_ID);
            }
        }
    }
}
